from django.shortcuts import render
from .models import *
from goods.serializer import *
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .serializer import *
# Create your views here.


class OrderInfoViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"

    def my_list(self,request, *args, **kwargs):
        # 1.获取所有的订单数据
        orders = self.get_queryset()

        # 2.序列化
        orders_ser = self.get_serializer(orders, many=True)

        # 3. 添加 skus 这个key
        temp = []
        for per_order in orders_ser.data:
            # 获取订单对象
            per_order_obj = orders.filter(order_id=per_order.get("order_id")).first()
            # 反向当前订单中的商品
            current_order_goods = per_order_obj.order_goods.all()

            # 序列化当前订单中的所有商品
            current_order_goods_ser = OrderGoodsSer(current_order_goods, many=True)

            # 4.处理所有的订单商品
            temp2 = []
            for per_order_good in current_order_goods_ser.data:

                # 获取当前 订单商品 对象
                per_order_good_obj = OrderGoods.objects.filter(id=per_order_good.get("id")).first()

                # 获取购买的商品对象，并进行序列化
                sku_dict = SKUSer(per_order_good_obj.sku).data

                per_order_good['sku'] = sku_dict

                # 追加到列表中
                temp2.append(per_order_good)

            # 添加skus
            per_order["skus"] = temp2

            # 将订单字典数据加入temo 列表
            temp.append(per_order)

        # my_data = {}

        return temp

    def retrieve(self, request, pk, *args, **kwargs):

        all_orders = self.my_list(request, pk, *args, **kwargs)

        for i in all_orders:
            if i.get("order_id") == pk:
                return Response(i)

        return Response({"code":"400", "msg":"订单数据不存在"})

    def update(self, request, pk, *args, **kwargs):

        # 获取前端传入的状态
        status = request.data.get("status")

        # 获取待更新的订单
        order = self.get_queryset().filter(order_id=pk).first()

        # 更新订单
        order.status = status
        order.save()

        return Response({"code":"200", "msg":"更新订单成功"})




